<?php

namespace app\common\model;

use app\common\utils\MysqlUtils;
use think\Model;

/**
 * Model公共基础类
 */
class CommonBaseModel extends Model
{
    public static function dataConn($config = 'default')
    {
        $obj = new Static;
        $obj->setConnection($config);
        return $obj;
    }

    /**
     * 只查询 is_deleted = 0 的数据,需要传入二维数组结构的 $where 条件
     * @param $where
     */
    public static function whereNotDelete($where = [])
    {
        $where[] = ['is_deleted', '=', 0];
        return parent::where($where);
    }

    /**
     * 获取所有数据的列表
     * @param $where
     * @return array
     */
    public static function getAllList($where = [])
    {
        return self::whereNotDelete($where)->select()->toArray();
    }

    /**
     * 获取数据总数
     * @param array $where
     * @return int
     */
    public static function getDataCount(array $where = []): int
    {
        return self::whereNotDelete($where)->count();
    }

    /**
     * 获取数据列表,分页处理
     * @param array $where
     * @param string $order_field
     * @param string $order_style
     * @param $page
     * @param $page_size
     * @return array
     */
    public static function getDataList(array $where, string $order_field = 'id', string $order_style = 'desc', $page = null, $page_size = null): array
    {
        $query = self::whereNotDelete($where)->order($order_field, $order_style);
        if ($page && $page_size) {
            $query->page($page, $page_size);
        }
        $result = $query->select()->toArray();
        return $result;
    }

    /**
     * 获取数据详情
     * @param array $where
     * @return array
     */
    public static function getDataInfo(array $where = []): array
    {
        return self::whereNotDelete($where)->findOrEmpty()->toArray();
    }

    /**
     * 根据ID获取数据详情
     * @param int $id
     * @return array
     */
    public static function getDataInfoById(int $id): array
    {
        return self::getDataInfo(['id' => $id]);
    }

    /**
     * 获取所有字段
     * @return array
     */
    public function getTableField(): array
    {
        return MysqlUtils::getTableField($this->getName());
    }

    /**
     * 获取需要更新的字段
     * @return array
     */
    public function getTableUpdateField(): array
    {
        return MysqlUtils::getTableUpdateField($this->getName());
    }

    /**
     * 对需要更新的字段进行过滤
     * @param array $params 请求的参数
     * @return void
     */
    public function filterParams(array &$params)
    {
        $table_field_array = MysqlUtils::getTableUpdateField($this->getName());
        foreach ($params as $k => $v) {
            if (!in_array($k, $table_field_array)) {
                unset($params[$k]);
            }
        }
    }

    /**
     * 根据ID更新数据
     * @param array $data 更新的字段数组
     * @param int $id ID
     * @return mixed
     */
    public static function updateDataById(array $data, int $id): bool
    {
        return parent::where('id', $id)->update($data);
    }

}